package com.framework.wz.wutong.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import com.framework.wz.wutong.base.BaseActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * @author wzq
 * @data 2019/7/10
 * @email wang_love152@163.com
 * @for
 */
public class SelectphotoUtils {

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static final int CROP_SMALL_PICTURE = 2;
    //图片路径
    public static Uri tempUri = null;

    /**
     * 拍照（Activity中调用此方法）
     */
    public static void takePicture1(BaseActivity baseActivity, File file) {
        if (ContextCompat.checkSelfPermission(baseActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 进入这儿表示没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(baseActivity, Manifest.permission.CAMERA)) {
                // 提示已经禁止
//                ToastUtil.longToast(mContext, getString(R.string.you_have_cut_down_the_permission));
            } else {
                ActivityCompat.requestPermissions(baseActivity, new String[]{Manifest.permission.CAMERA}, 100);
            }
        } else {
            Intent openCameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
//            file = new File(Environment.getExternalStorageDirectory(), "GLSH/image");
            /*tempUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                    "GLSH/image"));*/
//        //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= 24) {
                //android 7.0系统解决拍照的问题android.os.FileUriExposedException:file:///storage/emulated/0/test.txt
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
                tempUri = FileProvider.getUriForFile(baseActivity,
                        "com.framework.wz.wutong.fileprovider", file);
            } else {
                tempUri = Uri.fromFile(file);
            }

            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            if (isExistSd()) {
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
            }
            openCameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            baseActivity.startActivityForResult(openCameraIntent, TAKE_PICTURE);
        }
    }


    /**
     * 裁剪图片方法实现（Activity中调用此方法）
     *
     * @param uri
     */
    public static void startPhotoZoom1(Uri uri, final BaseActivity activity, Uri uritempFile) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, CROP_SMALL_PICTURE);
    }


    /**
     * 定义方法判断SD卡的存在性
     */
    public static boolean isExistSd() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }


    /**
     * 获取SD可用容量
     */
    private static long getAvailableStorage(Context context) {
        String root = context.getExternalFilesDir(null).getPath();
        StatFs statFs = new StatFs(root);
        long blockSize = statFs.getBlockSize();
        long availableBlocks = statFs.getAvailableBlocks();
        long availableSize = blockSize * availableBlocks;
        // Formatter.formatFileSize(context, availableSize);
        return availableSize;
    }


    /**
     * 采样率压缩图片
     */
    public static Bitmap getBitmap(Bitmap bitmap, int sampleSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sampleSize;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
        Bitmap bit = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
        Log.i("info", "图片大小：" + bit.getByteCount());//2665296  10661184
        return bit;
    }


}
